<template>
  <slide-view
    v-loading="loading"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    class="d-view"
    xs-empty-icon="nopermission"
    xs-empty-text="暂无权限"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div
      v-if="detail"
      direction="column"
      align="stretch"
      class="main">
      <wk-detail-header
        title="日志"
        :dropdowns="moreDropdowns"
        @command="moreDropdownsClick"
      />
      <div class="main__bd">
        <!-- 基本信息 -->
        <div class="main__bd--info">
          <div class="content">
            <log-fields-view
              :fields="fieldsDetail"
            />
          </div>

          <picture-list-view
            v-if="detail.img.length !== 0"
            :list="detail.img" />

          <flexbox v-if="detail.sendUserList && detail.sendUserList.length" class="send-list">
            <span class="send-list__label">发送给：</span>
            <!-- <span
              v-for="(item, index) in detail.sendUserList"
              :key="index"
              class="send-list__user">
              <xr-avatar
                :id="item.userId"
                :name="item.realname"
                :size="32"
                :src="item.img"
                :disabled="false"
                trigger="hover" />
            </span> -->
            <el-tooltip
              v-for="(item, index) in showSendUserList"
              :key="index"
              :class="{'is-close': allSendUserDeptList.length > maxSendShowCount}"
              placement="top"
              :content="item.realname || item.name"
              class="send-user">
              <xr-avatar
                :id="item.userId"
                :name="item.realname || item.name"
                :size="32"
                :disabled="!item.userId"
                :src="item.img" />
            </el-tooltip>
            <el-dropdown
              v-if="allSendUserDeptList.length > maxSendShowCount"
              trigger="click"
              :hide-on-click="false">
              <el-button class="dropdown-btn">
                +{{ allSendUserDeptList.length - maxSendShowCount }}
              </el-button>
              <el-dropdown-menu slot="dropdown" class="send-list-dropdown">
                <el-dropdown-item
                  v-for="(item,index) in closeSendUserDeptList"
                  :key="index"
                  class="send-list-dropdown-list">
                  <p class="send-list-dropdown-text">{{ item.realname || item.name }} </p>
                  <!-- <i
                  class="el-icon-close send-list-dropdown-i"
                  @click="deleteSendList(item, index + 5)" /> -->
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </flexbox>

          <!-- 附件 -->
          <div v-if="detail.file.length" class="section">
            <div class="section__hd">
              <!-- <i class="wukong wukong-file" /> -->
              <span>附件</span>
              <span>({{ detail.file.length }})</span>
            </div>
            <div class="section__bd">
              <file-cell :file-list="detail.file" />
            </div>
          </div>
          <fav-list
            :is-favour="detail.isFavour"
            :data="detail.favourUser"
            @fav="favourClick"
          />
        </div>

        <!-- 回复 -->
        <el-tabs
          value="commont"
          type="border-card"
          class="commont">
          <el-tab-pane
            label="评论"
            name="commont">
            <reply-comment
              ref="f_reply"
              v-loading="commentLoading"
              :props="{
                contentType: commentListProps.contentType
              }"
              @toggle="closeOtherReply"
              @reply="handleReply" />
            <comment-list
              v-if="replyList.length > 0"
              ref="comment_list"
              :props="commentListProps"
              :list="replyList"
              @delete="deleteComment"
              @close-other-reply="$refs.f_reply.toggleFocus(true)" />
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>
  </slide-view>
</template>

<script>
import {
  journalQueryByIdAPI,
  oaLogFavourOrCancelAPI,
  journalInformationAPI
} from '@/api/oa/journal'
import {
  setCommentAPI,
  deleteCommentAPI,
  queryCommentListAPI
} from '@/api/oa/common'

import SlideView from '@/components/SlideView'
import PictureListView from '@/components/PictureListView'
import FileCell from '@/components/FileCell'
import ReplyComment from '@/components/ReplyComment'
import CommentList from '@/components/CommentList'
import FavList from './FavList'
import LogFieldsView from './LogFieldsView'
import WkDetailHeader from '@/components/Page/WkDetailHeader'

import { mapGetters } from 'vuex'

export default {
  // 日志详情
  name: 'LogDetail',
  components: {
    SlideView,
    PictureListView,
    FileCell,
    ReplyComment,
    CommentList,
    FavList,
    WkDetailHeader,
    LogFieldsView
  },
  props: {
    id: [String, Number],
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    }
  },
  data() {
    return {
      loading: false,
      detail: null,
      fieldsDetail: [], // 自定义字段等详情
      // 简报信息
      reportList: [
        {
          type: 'customer',
          key: 'customerCount',
          info: '新增客户',
          count: 0,
          name: '新增客户 0'
        },
        {
          type: 'business',
          key: 'businessCount',
          info: '新增商机',
          count: 0,
          name: '新增商机 0'
        },
        {
          type: 'contract',
          key: 'contractCount',
          info: '新增合同',
          count: 0,
          name: '新增合同 0'
        },
        {
          type: 'receivables',
          key: 'receivablesMoney',
          info: '新增回款',
          count: 0,
          name: '新增回款 0'
        },
        {
          type: 'record',
          key: 'recordCount',
          info: '新增跟进记录',
          count: 0,
          name: '新增跟进记录 0'
        }
      ],

      // 回复
      commentLoading: false,
      replyList: [],
      maxSendShowCount: 5,

      moreDropdowns: [{
        command: 'print',
        name: '打印'
      }]
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    // 评论列表配置
    commentListProps() {
      return {
        addRequest: setCommentAPI, // 添加请求和参数
        addParams: {
          titleName: '',
          typeId: this.id,
          type: '2'
        }, // 3 知识库 2 日志 1 任务
        replyKey: 'pid', // 日志 任务 pid  阶段 replyId
        replyValueKey: 'userId', // 获取值的keys 日志 任务 userId  阶段 user.userId
        deleteRequest: deleteCommentAPI, // 删除请求和参数
        deleteParams: null,
        contentType: 'rich'
      }
    },

    // 展示的发送人
    showSendUserList() {
      return this.allSendUserDeptList.slice(0, this.maxSendShowCount)
    },

    // 全部发送人
    allSendUserDeptList() {
      const defaultSendUserList = (this.detail.sendUserList || []).map(item => {
        item.disabled = true
        return item
      })
      const defaultSendDeptList = (this.detail.sendDeptList || []).map(item => {
        item.disabled = true
        return item
      })

      return defaultSendUserList.concat(defaultSendDeptList)
    },

    // 闭合起来的员工和部门
    closeSendUserDeptList() {
      return this.allSendUserDeptList.slice(this.maxSendShowCount)
    }
  },
  watch: {
    id() {
      this.viewAfterEnter()
    }
  },
  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * @description: 获取字段信息
     * @return {*}
     */
    getFieldsInfo() {
      this.loading = true
      journalInformationAPI({ id: this.id })
        .then(res => {
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * @description: 更多事件
     * @return {*}
     */
    moreDropdownsClick(command) {
      if (command === 'print') {
        this.$router.push({
          name: 'logPrint',
          query: {
            id: this.detail.logId,
            templateId: this.detail.categoryId
          }
        })
      }
    },

    /**
     * 页面展示发请求
     */
    viewAfterEnter() {
      this.detail = null
      this.getDetail()
      this.getCommentList()
    },

    /**
     * 详情
     */
    getDetail() {
      this.loading = true

      Promise.all([
        journalQueryByIdAPI({ logId: this.id }),
        journalInformationAPI({ id: this.id })
      ]).then(resArr => {
        if (resArr[0]) {
          this.detail = resArr[0].data
        }

        if (resArr[1]) {
          this.fieldsDetail = resArr[1].data || []
        }

        this.loading = false
      }).catch((e) => {
        console.error(e)
        this.loading = false
      })
    },

    /**
     * 关闭页面
     */
    hideView() {
      this.$emit('close')
      this.$emit('hide-view')
    },

    /**
     * 评论逻辑
     */
    getCommentList() {
      queryCommentListAPI({
        typeId: this.id,
        type: 2 // 任务1 日志2
      })
        .then(res => {
          const list = res.data || []
          this.replyList = list
          // this.replyList = list.sort((a, b) => {
          //   return new Date(b.createTime) - new Date(a.createTime)
          // }) || []
        })
        .catch(() => {})
    },

    closeOtherReply(flag) {
      if (!flag && this.$refs.comment_list) {
        this.$refs.comment_list.closeReply()
      }
    },

    deleteComment(index) {
      this.replyList.splice(index, 1)
    },

    /**
     * 日志评论
     */
    handleReply(data) {
      this.commentLoading = true
      setCommentAPI({
        content: data,
        ...this.commentListProps.addParams
      }).then(res => {
        res.data.user = {
          userId: this.userInfo.userId,
          realname: this.userInfo.realname,
          img: this.userInfo.img
        }
        res.data.childCommentList = []
        // this.$emit('add-comment', {
        //   data: res.data,
        //   index: this.index
        // })
        this.$refs.f_reply.commentsTextarea = ''
        this.replyList.push(res.data)
        this.commentLoading = false
      }).catch(() => {
        this.commentLoading = false
      })
    },

    /**
     * 点赞
     */
    favourClick() {
      oaLogFavourOrCancelAPI({
        isFavour: !this.detail.isFavour,
        logId: this.detail.logId
      }).then(res => {
        const resData = res.data || {}
        this.detail.isFavour = resData.isFavour
        this.detail.favourUser = resData.favourUser
      })
        .catch(() => {})
    }

  }
}
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  height: 100%;
  background: #f5f6f9;

  &__bd {
    height: calc(100% - 40px);
    overflow: auto;

    &--info {
      padding: 0 20px 10px;
      background: white;
    }
  }
}

.d-view {
  position: fixed;
  top: $--detail-view-top;
  right: 0;
  bottom: 0;
  width: $--detail-width-base;
  min-width: 926px;
  padding: 15px;
  padding: 0 !important;
  background-color: white;
}

// 日志内容
.content {
  padding-top: 30px;

  .content-box {
    margin-bottom: 16px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 16px;
    }

    .content-title {
      margin-bottom: 8px;
      color: $--color-n200;
    }

    .content-text {
      line-height: 1.5;
      word-wrap: break-word;
      white-space: pre-wrap;
    }
  }
}

.wk-detail-header {
  padding: 30px 20px 0;
  background: white;
}

.send-list {
  padding: 8px 0;

  &__label {
    color: $--color-n200;
  }

  &__user {
    position: relative;
    display: inline-block;
  }

  &__user + &__user {
    margin-left: 7px;
  }
}

// 详情其他模块
.section {
  padding: 10px 0;

  &__hd {
    span {
      font-size: 16px;
      font-weight: 600;
    }

    .wk {
      margin-right: 5px;
      font-size: 15px;
      color: #363636;
    }
  }

  &__bd {
    padding-left: 0;
    margin-top: 15px;
  }
}

// 销售简报
.report-menu {
  padding: $--interval-base;
  background-color: $--background-color-base;
  border-radius: $--border-radius-base;
}

// 详情
.commont {
  margin-bottom: 50px;
  box-shadow: none;

  ::v-deep .el-tabs__item {
    top: 2px;
    margin-top: -2px;
    font-size: 12px;
  }

  ::v-deep .el-tabs__nav-scroll {
    min-height: 39px;
  }

  ::v-deep .el-tabs__item.is-active {
    border-top: 2px solid $--color-primary;
  }

  ::v-deep .el-tabs {
    height: calc(100% - 15px) !important;
  }

  // ::v-deep .el-tabs__content {
  //   height: calc(100% - 40px) !important;
  //   padding: 0;
  //   overflow: hidden;
  //   position: relative;

  //   .el-tab-pane {
  //     height: 100%;
  //     overflow: hidden;
  //   }
  // }
}

// 发送人
.send-user {
  position: relative;
  display: inline-block;

  &.is-close {
    border: 3px solid #fff;
    border-radius: 50%;
  }

  &.is-close + &.is-close {
    margin-left: -13px !important;
  }
}

.send-user + .send-user {
  margin-left: 7px;
}

.send-list-dropdown {
  width: 200px;
  max-height: 300px;
  overflow-y: auto;

  &-list {
    position: relative;
    display: flex;
    align-items: center;
    padding-top: 5px;
    padding-bottom: 5px;
    border-left: 2px solid $--color-white;

    &:hover {
      background: $--color-n20 !important;
      border-left: 2px solid $--color-b400;
    }

    &:hover .send-list-dropdown-i {
      display: inline-block;
      color: $--color-n500;
    }

    &:hover .send-list-dropdown-text {
      color: $--color-n500;
    }
  }

  &-text {
    display: inline-block;
    width: 80px;
    height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &-i {
    position: absolute;
    top: 18px;
    right: 10px;
    display: none;
    margin-left: 60px;
  }
}

</style>
